import { acceptHMRUpdate, defineStore } from 'pinia'
import { ref } from 'vue'
import { adminLogin, getAdminDetail } from '~/api/admin'

export const useAdminStore = defineStore('admin', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const adminInfo = ref<any>(null)
  const loading = ref<boolean>(false)
  const loginError = ref<string>('')
  const rememberedAdminname = ref<string>(localStorage.getItem('adminname') || '')
  const isRemembered = ref<boolean>(localStorage.getItem('remember') === 'true')

  // 获取
  const isLoggedIn = () => !!token.value

  // 动作
  // 登录
  async function login(adminname: string, password: string, remember: boolean = false) {
    loading.value = true
    loginError.value = ''

    try {
      const result = await adminLogin(adminname, password)

      // 保存token
      token.value = result.token || ''
      localStorage.setItem('token', token.value)

      // 保存用户信息
      adminInfo.value = result || ''

      // 保存记住的账号
      if (remember) {
        rememberedAdminname.value = adminname
        isRemembered.value = true
        localStorage.setItem('remember', 'true')
      }
      else {
        rememberedAdminname.value = ''
        isRemembered.value = false
        localStorage.removeItem('remember')
      }

      // 获取管理员信息
      if (token.value) {
        await fetchAdminInfo()
      }

      return { success: true }
    }
    catch (error: any) {
      loginError.value = error.message || '登录失败，请重试'
      return { success: false, error: loginError.value }
    }
    finally {
      loading.value = false
    }
  }

  // 获取管理员信息
  async function fetchAdminInfo() {
    if (!token.value)
      return null

    try {
      const adminid = localStorage.getItem('adminid') || ''
      if (!adminid)
        return null

      const result = await getAdminDetail(adminid)
      adminInfo.value = result
      return adminInfo.value
    }
    catch (error) {
      console.error('获取管理员信息失败:', error)
      return null
    }
  }

  // 登出
  function logout() {
    token.value = ''
    adminInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('adminid')
    // 不清除记住的账号信息
  }

  return {
    // 状态
    token,
    adminInfo,
    loading,
    loginError,
    rememberedAdminname,
    isRemembered,

    // 获取器
    isLoggedIn,

    // 动作
    login,
    fetchAdminInfo,
    logout,
  }
}, {
  // 启用持久化存储
  persist: {
    key: 'adminInfo',
    pick: ['adminInfo'],
  },
})

// HMR传递
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useAdminStore, import.meta.hot))
}
